<template>
  <div id="questionSubmitView">
    <!-- 页面标题 -->
    <!-- 搜索区域 -->
    <a-card class="search-card" :bordered="true">
      <template #title>
        <div class="card-title">
          <icon-filter />
          <span>筛选条件</span>
        </div>
      </template>
      <a-form :model="searchParams" layout="horizontal">
        <a-row :gutter="16">
          <a-col :span="10">
            <a-form-item
              field="language"
              label="编程语言"
              tooltip="请选择编程语言"
            >
              <a-select
                v-model="searchParams.language"
                placeholder="选择编程语言"
                allow-clear
              >
                <a-option>java</a-option>
                <a-option>cpp</a-option>
                <a-option>go</a-option>
                <a-option>html</a-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col :span="10">
            <a-form-item field="status" label="判题状态">
              <a-select
                v-model="searchParams.status"
                placeholder="选择判题状态"
                allow-clear
              >
                <a-option :value="0">等待判题</a-option>
                <a-option :value="1">正在判题</a-option>
                <a-option :value="2">判题完成</a-option>
                <a-option :value="3">判题失败</a-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col :span="4" style="display: flex; align-items: flex-end">
            <a-space>
              <a-button @click="resetSearch">
                <template #icon><icon-refresh /></template>
                重置
              </a-button>
              <a-button type="primary" @click="doSearch" status="success">
                <template #icon><icon-search /></template>
                搜索
              </a-button>
            </a-space>
          </a-col>
        </a-row>
      </a-form>
    </a-card>

    <!-- 提交记录表格 -->
    <a-card class="table-card" :bordered="true">
      <template #title>
        <div class="card-title">
          <icon-history />
          <span>提交历史</span>
          <a-tag v-if="isPolling" color="green" style="margin-left: 8px"
            >实时刷新中</a-tag
          >
        </div>
      </template>

      <a-table
        :ref="tableRef"
        :columns="columns"
        :data="dataList"
        :loading="tableLoading"
        row-key="id"
        :pagination="{
          showTotal: true,
          pageSize: searchParams.pageSize,
          current: searchParams.current,
          total,
          position: ['bottomCenter'],
        }"
        :row-class-name="
          (_record: any, index: number) => (index % 2 === 0 ? 'even-row' : 'odd-row')
        "
        @page-change="onPageChange"
      >
        <template #language="{ record }">
          <a-tag :color="languageColor(record.language)">
            {{ record.language }}
          </a-tag>
        </template>

        <template #judgeInfo="{ record }">
          <a-descriptions
            :data="transformJudgeInfo(record.judgeInfo || {})"
            layout="inline-horizontal"
            size="small"
            :column="1"
            class="judge-info"
          />
        </template>

        <template #resultStatus="{ record }">
          <a-tag :color="resultStatusColor(record.judgeInfo?.message)">
            {{ record.judgeInfo?.message || "等待中" }}
          </a-tag>
        </template>

        <template #status="{ record }">
          <a-tag :color="statusColor(record.status)">
            {{ formatStatus(record.status) }}
          </a-tag>
        </template>

        <template #createTime="{ record }">
          <div class="time-cell">
            {{ moment(record.createTime).format("YYYY-MM-DD HH:mm:ss") }}
          </div>
        </template>

        <template #optional="{ record }">
          <a-button
            type="text"
            size="small"
            @click="handleViewCode(record.id, record.language)"
          >
            <template #icon><icon-eye /></template>
            查看
          </a-button>
        </template>

        <template #empty>
          <div class="empty-state">
            <icon-empty />
            <p>暂无提交记录</p>
          </div>
        </template>
      </a-table>
    </a-card>

    <a-modal
      v-model:visible="showCodeModal"
      title="提交代码"
      :footer="null"
      width="800px"
    >
      <AnswerCodeEditor
        :key="codeContent"
        :code="codeContent"
        :handleChange="() => {}"
        style="width: 100%; height: 50vh"
        :language="codeLanguage"
      />
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watchEffect } from "vue";
import {
  QuestionControllerService,
  QuestionSubmitQueryRequest,
  UserControllerService,
} from "../../../generated";
import message from "@arco-design/web-vue/es/message";
import moment from "moment";
import { useRouter } from "vue-router";
import {
  IconFilter,
  IconHistory,
  IconSearch,
  IconRefresh,
  IconCode,
  IconEye,
  IconEmpty,
} from "@arco-design/web-vue/es/icon";
import AnswerCodeEditor from "@/components/AnswerCodeEditor.vue";
// import { getCodeByQuestionSubmitId } from "../../../generated/services/QuestionControllerService";
const tableRef = ref();
const dataList = ref([]);
const total = ref(0);
const questionId = ref(0);
const userId = ref(0);
const tableLoading = ref(false);
const isPolling = ref(true);
const router = useRouter();

const searchParams = ref<QuestionSubmitQueryRequest>({
  questionId: undefined,
  language: undefined,
  status: undefined,
  pageSize: 10,
  current: 1,
});

const loadData = async () => {
  tableLoading.value = true;
  try {
    const res =
      await QuestionControllerService.listQuestionSubmitByPageUsingPost({
        ...searchParams.value,
        sortField: "createTime",
        sortOrder: "descend",
      });
    if (res.code === 0) {
      dataList.value = res.data.records;
      total.value = res.data.total;
      questionId.value = res.data.questionId;
      userId.value = res.data.userId;
      dataList.value = res.data.records.map((item: any) => {
        if (item.questionId === "1869392320718675970") {
          item.questionId = "两数之和";
        }
        if (item.userId === "1908152443967729665") {
          item.userId = "Jay";
        }
        if (item.userId === "1886334158867619845") {
          item.userId = "AI助手";
        }

        return item;
      });
    } else {
      message.error("加载失败，" + res.message);
    }
  } catch (error) {
    message.error("请求失败，请检查网络");
  } finally {
    tableLoading.value = false;
  }
};

watchEffect(() => {
  loadData();
});

onMounted(() => {
  loadData();
  startPolling();
});

onUnmounted(() => {
  stopPolling();
});

const POLLING_INTERVAL = 2000;
// 明确类型定义
let pollingTimer: number | null = null;

const startPolling = () => {
  isPolling.value = true;
  pollingTimer = window.setInterval(() => {
    // 只有当存在等待中或判题中的提交时才自动刷新
    const needRefresh = dataList.value.some(
      (item: any) => item.status === 0 || item.status === 1
    );
    if (needRefresh) {
      loadData();
    }
  }, POLLING_INTERVAL);
};

const stopPolling = () => {
  if (pollingTimer !== null) {
    window.clearInterval(pollingTimer);
    pollingTimer = null;
  }
  isPolling.value = false;
};

// 切换自动刷新状态
const togglePolling = () => {
  if (pollingTimer) {
    stopPolling();
  } else {
    startPolling();
  }
};

// 搜索按钮点击事件
const doSearch = () => {
  searchParams.value.current = 1; // 重置页码
  loadData();
};

// 重置搜索条件
const resetSearch = () => {
  searchParams.value = {
    questionId: undefined,
    language: undefined,
    status: undefined,
    pageSize: 10,
    current: 1,
  };
  doSearch();
};

// 查看提交详情
const viewSubmission = (record: any) => {
  message.info("查看提交记录: " + record.id);
  // 实际项目中这里可以跳转到详情页或弹出模态框
};

const columns = [
  { title: "提交号", dataIndex: "id", align: "center", width: 200 },
  {
    title: "题目",
    dataIndex: "questionId",
    align: "center",
    ellipsis: true,
    width: 100,
  },
  {
    title: "语言",
    dataIndex: "language",
    slotName: "language",
    align: "center",
    width: 100,
  },
  {
    title: "消耗情况",
    slotName: "judgeInfo",
    align: "center",
    width: 130,
  },
  {
    title: "结果",
    slotName: "resultStatus",
    align: "center",
    width: 120,
  },
  {
    title: "状态",
    slotName: "status",
    align: "center",
    width: 100,
  },
  {
    title: "提交者",
    dataIndex: "userId",
    align: "center",
    width: 80,
  },
  {
    title: "创建时间",
    slotName: "createTime",
    align: "center",
    width: 130,
  },
  {
    title: "操作",
    slotName: "optional",
    align: "center",
    width: 80,
  },
];

const onPageChange = (page: number) => {
  searchParams.value.current = page;
};

const transformJudgeInfo = (judgeInfo: Record<string, any>) => {
  if (!judgeInfo) return [];

  const result = [];

  // 将时间消耗和内存消耗合并到一行
  if (
    Object.prototype.hasOwnProperty.call(judgeInfo, "time") ||
    Object.prototype.hasOwnProperty.call(judgeInfo, "memory")
  ) {
    result.push({
      value: `${judgeInfo.time || 0}ms / ${judgeInfo.memory || 0}kb`,
    });
  }

  // 添加除时间和内存外的其他信息
  Object.keys(judgeInfo)
    .filter((key) => key !== "message" && key !== "time" && key !== "memory")
    .forEach((key) => {
      result.push({
        label: key,
        value: judgeInfo[key],
      });
    });

  return result;
};

const formatStatus = (status: number) => {
  switch (status) {
    case 0:
      return "等待判题";
    case 1:
      return "正在判题";
    case 2:
      return "判题完成";
    case 3:
      return "判题失败";
    default:
      return "未知状态";
  }
};

const statusColor = (status: number) => {
  switch (status) {
    case 0:
      return "gray";
    case 1:
      return "blue";
    case 2:
      return "green";
    case 3:
      return "red";
    default:
      return "gray";
  }
};

const resultStatusColor = (message: string) => {
  if (!message) return "gray";
  if (message === "Accepted") return "green";
  if (message === "Wrong Answer") return "red";
  if (message === "Compile Error") return "orange";
  if (message === "Memory Limit Exceed") return "red";
  if (message === "Time Limit Exceeded") return "red";
  return "gray";
};

const languageColor = (language: string) => {
  if (!language) return "gray";
  if (language === "java") return "blue";
  if (language === "cpp") return "purple";
  if (language === "go") return "green";
  if (language === "html") return "orange";
  return "gray";
};

const showCodeModal = ref(false);
const codeContent = ref("");
const codeLanguage = ref("java");
const loadingCode = ref(false);

const handleViewCode = async (questionSubmitId: number, language = "java") => {
  loadingCode.value = true;
  codeContent.value = "";
  codeLanguage.value = language;
  try {
    const res = await QuestionControllerService.getCodeByQuestionSubmitId(
      questionSubmitId
    );
    if (res.code === 0) {
      codeContent.value = res.data || "";
      showCodeModal.value = true;
    } else {
      message.error(res.message || "获取代码失败");
    }
  } finally {
    loadingCode.value = false;
  }
};
</script>

<style scoped>
#questionSubmitView {
  max-width: 1280px;
  margin: 0 auto;
  padding: 20px;
}

/* 页面标题区域 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-title {
  margin: 0;
  font-size: 24px;
  color: #333;
  font-weight: 600;
}

.card-title {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #165dff;
  font-weight: 500;
}

.search-card,
.table-card {
  margin-bottom: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

/* 表格样式 */
:deep(.even-row) {
  background-color: #f9f9f9;
}

:deep(.odd-row) {
  background-color: #ffffff;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
  color: #86909c;
}

.empty-state :deep(svg) {
  font-size: 48px;
  margin-bottom: 16px;
  color: #c2c7d0;
}

.empty-state p {
  margin-bottom: 16px;
}

/* 优化消耗情况显示 */
.judge-info {
  white-space: nowrap;
}

.judge-info :deep(.arco-descriptions-item-label) {
  color: #666;
  font-weight: 500;
}

.judge-info :deep(.arco-descriptions-item-value) {
  color: #333;
  font-weight: 600;
}

.time-cell {
  white-space: nowrap;
  color: #666;
  font-family: Monaco, monospace;
  font-size: 12px;
}
</style>
